import React from "react";
import { connect } from "react-redux";
import fetch from "../../utils/fetch";
import { Input, Button, Row, Col, Select, Icon, Modal, Form } from "antd";
import PostMsgTable from "./PostMsgTable";
import PostMsgModal from "./PostMsgModal";
import { cloneDeep } from "lodash";
import "./index.scss";
import { fetchPostMsgs } from '../../actions/appData';

const Option = Select.Option;
const FormItem = Form.Item;
class PostMsgManage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showQuickJumper: true
      },
      selectedRowKeys: [],
      showPostMsgModal: false,
      selectPostMsg: {},
      action: "add",
      filterData: {
        _id: "",
        content: "",
        postId: "",
      },
      modalData: {},
      showLikeModal: false,
      showCmtModal: false,
    };
  }

  componentDidMount() {
    const { pagination } = this.state;
    const { current, pageSize } = pagination;
    this.getPostMsgService(current, pageSize);
  }

  componentWillReceiveProps(nextProps) {
    const newUser = nextProps.user;
    const user = this.props.user;
    if (!user.name && newUser.name) {
      this.onSearch(nextProps);
    }
  }

  getPostMsgService = (current, pageSize, filterData) => {
    fetch("/api/getPostMsgs", {
      current,
      pageSize,
      ...filterData
    }).then(data => {
      const { pagination } = this.state;
      pagination.total = data.total;
      pagination.current = current;
      this.setState({ list: data.list, pagination });
    });
  };

  handleCancel = () => {
    this.setState({ showPostMsgModal: false });
    // this.onSearch();
  };

  removePostMsgs = () => {
    const { dispatch } = this.props;
    const { selectedRowKeys: postMsgIds } = this.state;
    fetch("/api/removePostMsgs", { postMsgIds }).then(() => {
      this.onSearch();
      this.setState({ selectedRowKeys: [] });
    });
  };

  editPostMsg = postMsg => {
    this.setState({
      showPostMsgModal: true,
      selectPostMsg: postMsg,
      action: "edit"
    });
  };

  onRowSelect = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  resetFilter = () => {
    this.setState(
      {
        filterData: {
          _id: "",
          content: "",
          postId: ""
        }
      },
      this.onSearch
    );
  };

  onSearch = (props) => {
    // const { user } = props || this.props;
    const filterData = cloneDeep(this.state.filterData);
    const { current, pageSize } = this.state.pagination;
    const { content, _id, postId } = filterData;
    if (content) {
      filterData.content = {
        $regex: content,
        $options: "i"
      };
    } else {
      delete filterData.content;
    }
    if (!_id) {
      delete filterData._id;
    }
    if (!postId) {
      delete filterData.postId;
    }
    this.getPostMsgService(current, pageSize, filterData);
  };

  onFilterChange = (value, key) => {
    const { filterData } = this.state;
    filterData[key] = value;
    this.setState({ filterData });
  };
  
  noPassPostMsg = (postMsg) => {
    fetch("/api/noPassPostMsg", {_id: postMsg._id}).then(() => {
      this.onSearch();
    });
  };

  removePostMsg = (postMsgIds) => {
    fetch("/api/removePostMsgs", {postMsgIds}).then(() => {
      this.onSearch();
    });
  };

  onModalChange = (key, value) => {
    const { modalData } = this.state;
    modalData[key] = value;
    this.setState({ modalData })
  }

  handleLike = () => {
    const { modalData, selectPostMsg } = this.state;
    const { users } = this.props;
    const params = { ...modalData };
    params.postMsgId = selectPostMsg._id;
    params.user = users.filter(u => u._id === modalData.user)[0];
    fetch("/api/likePostMsg", params).then(() => {
      this.onSearch();
      this.setState({ showLikeModal: false });
    });
  };

  handleCmt = () => {
    const { modalData, selectPostMsg } = this.state;
    const { users } = this.props;
    const params = { ...modalData };
    params.postMsgId = selectPostMsg._id;
    params.user = users.filter(u => u._id === modalData.user)[0];
    fetch("/api/cmtPostMsg", params).then(() => {
      this.onSearch();
      this.setState({ showCmtModal: false });
    });
  };

  render() {
    const {
      list,
      pagination,
      selectedRowKeys,
      showPostMsgModal,
      selectPostMsg,
      filterData,
      action,
      modalData,
      showLikeModal,
      showCmtModal,
    } = this.state;

    return (
      <div className="postMsg-manage-wrapper">
        <Row className="search-bar" gutter={16}>
          <Col span={6}>
            <Input
              placeholder="输入id"
              value={filterData._id}
              onChange={e => this.onFilterChange(e.target.value, "_id")}
            />
          </Col>
          <Col span={6}>
            <Input
              placeholder="输入内容"
              value={filterData.content}
              onChange={e => this.onFilterChange(e.target.value, "content")}
            />
          </Col>
          <Col span={6}>
            <Input
              placeholder="输入帖子ID"
              value={filterData.postId}
              onChange={e => this.onFilterChange(e.target.value, "postId")}
            />
          </Col>
          <Button onClick={() => this.onSearch()}>
            <Icon type="search" />
          </Button>
          <Button onClick={this.resetFilter}>
            <Icon type="close" />
          </Button>
        </Row>
        <Row className="tool-bar">
          <Button
            size="small"
            onClick={() =>
              this.setState({
                showPostMsgModal: true,
                selectPostMsg: {},
                action: "add"
              })}
          >
            <Icon type="plus" />
          </Button>
          {selectedRowKeys.length > 0 && (
            <Button
              type="primary"
              size="small"
              style={{ marginLeft: 8 }}
              onClick={this.removePostMsgs}
            >
              <Icon type="close" />
            </Button>
          )}
        </Row>
        <PostMsgTable
          list={list}
          pagination={pagination}
          selectedRowKeys={selectedRowKeys}
          getPostMsgService={this.getPostMsgService}
          editPostMsg={this.editPostMsg}
          onRowSelect={this.onRowSelect}
          setTop={this.setTopPostMsg}
          noPass={this.noPassPostMsg}
          remove={this.removePostMsg}
        />
        {showPostMsgModal && (
          <PostMsgModal
            visible={showPostMsgModal}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            onSearch={this.onSearch}
            postMsg={selectPostMsg}
            user={this.props.user}
            users={this.props.users}
            action={action}
            dispatch={this.props.dispatch}
          />
        )}
        <Modal
          title="点赞"
          visible={showLikeModal}
          onOk={this.handleLike}
          onCancel={() => this.setState({ showLikeModal: false })}
        >
          <FormItem label={'选择用户'}>
            <Select style={{ width: '100%' }} value={modalData.user} onChange={(value) => this.onModalChange('user', value)} placeholder={"请选择用户"}>
              {this.props.users.map(o => (
                <Option key={o._id} value={o._id}>
                  {o.nickname}
                </Option>
              ))}
            </Select>
          </FormItem>
        </Modal>

        <Modal
          title="评论"
          visible={showCmtModal}
          onOk={this.handleCmt}
          onCancel={() => this.setState({ showCmtModal: false })}
        >
          <FormItem label={'选择用户'}>
            <Select style={{ width: '100%' }} value={modalData.user} onChange={(value) => this.onModalChange('user', value)} placeholder={"请选择用户"}>
              {this.props.users.map(o => (
                <Option key={o._id} value={o._id}>
                  {o.nickname}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem label={'评论内容'}>
            <Input value={modalData.cmt} onChange={(e) => this.onModalChange('cmt', e.target.value)} placeholder={"请选择用户"} />
          </FormItem>
        </Modal>
      </div>
    );
  }
}
function mapStateToProps(state) {
  const { user, appData } = state;
  return {
    user,
    users: appData.users,
  };
}
export default connect(mapStateToProps)(PostMsgManage);
